<template>
	<app-layout>
		<view class="">
			<!-- 顶部自定义导航 -->
			<tn-nav-bar>签到</tn-nav-bar>
			<view class="sign tn-padding" :style="{paddingTop: vuex_custom_bar_height + 'px'}">
				<!-- 图标logo/头像 -->
				<view class=" userinfo tn-bg-white ">
					<view class="">
						<image v-if="userinfo.face" class="avatar" :src="userinfo.face" mode="aspectFill">
						</image>
						<view v-else class="avatar">{{userinfo.username.substr(0,2)}}</view>
					</view>
					<view class="tn-padding-right">
						<view class="tn-padding-right tn-padding-left-sm">
							<text class="tn-color-cat  tn-text-bold">{{userinfo.username }} </text>
						</view>
						<view class="tn-padding-right tn-padding-top-xs tn-padding-left-sm tn-text-ellipsis">
							<text class="">{{userinfo.gsxz}}</text>
							<text v-if="userinfo.iphone"
								class=" tn-padding-left-sm tn-text-md">{{userinfo.iphone}}</text>
						</view>
					</view>
				</view>
				<view class="signbg tn-bg-white">
					<view class="desc">
						<view class="tn-margin-bottom-sm">
							签到需拍摄人脸核验，请确保正对手机，光线充足
						</view>
						<view>当前核验：{{userinfo.username}}</view>
					</view>

					<view class="btns" v-if="isaddress" @click="showloading">
						<tn-image-upload ref="upload" :formData="formData" :action="action" @on-error="uperror"
							:customBtn="true" :autoUpload="!!1" @on-success="upsuccess" :Scamera="setting.camera"
							:showUploadList="setting.showUploadList" :sourceType="setting.sourceType">
							<view slot="addBtn">
								<view class="signbtn">
									<view class="text">签到</view>
									<view v-if="time" class="time">{{time}}</view>
								</view>
							</view>
						</tn-image-upload>
					</view>
					<view class="signbtn2" v-else>
						<view class="text">加载中 </view>
					</view>
					<!-- <view class="address">
						<text class="tn-icon-location-fill"></text>
						<view>
							{{address||'暂未获取到位置信息'}}
						</view>
					</view> -->
				</view>

			</view>
			<view class='tn-tabbar-height'></view>

		</view>
	</app-layout>
</template>

<script>
	import {
		mapGetters,
		mapState
	} from "vuex";
	var QQMapWX = require('../../core/qqmap-wx-jssdk.min.js');
	var qqmapsdk;
	export default {
		name: 'signadd',
		data() {
			return {
				mfid: '',
				time: '',
				lat: '',
				lng: '',
				url: '',
				province: '',
				city: '',
				county: '',
				street: '',
				address: '',
				isaddress: false,
				action: this.$api.upload.index,
				setting: {
					sourceType: ['camera'],
					camera: 'front',
					showUploadList: false
				},
				isopencar: false,
				timer: '',

			}
		},
		onLoad(options) {
			let t = this;
			this.mfid = options.mfid ? options.mfid : this.mfid;
			if (!this.mfid) {
				uni.showModal({
					title: '提示',
					content: '用户ID不存在，请稍后再试',
					showCancel: false,
					success() {
						t.goBack()
					}
				})
			}
			// 实例化API核心类
			qqmapsdk = new QQMapWX({
				key: 'RTMBZ-RSIKB-IAPUF-NCGPZ-6OVP2-RNFTO'
			});
			if (this.timer) {
				clearInterval(this.timer)
			} else {
				this.timer = setInterval(() => {
					t.time = t.$utils.datetime('Y-m-d h:i:s')
				}, 1000)
			}
		},
		computed: {
			...mapState({
				userinfo: state => state.userinfo,
			})
		},
		onShow() {
			if (this.isopencar == true) {
				this.closeloading()
			}
			if (!this.userinfo) {
				this.$user.getInfo()
			}
			this.getLocation();
		},
		onReady() {

		},
		methods: {
			showloading() {
				this.isopencar = true
				this.$t.message.loading('正在打开摄像头')
			},
			closeloading() {
				this.isopencar = false
				this.$t.message.closeLoading()
			},
			upsuccess(e) {
				let t = this;
				t.url = e.url;
				t.$t.message.loading('正在核对人像')
				t.$request({
					url: t.$api.user.checkface,
					method: 'POST',
					data: {
						image: t.url,
						mfid: t.mfid
					}
				}).then(response => {
					t.$t.message.closeLoading()
					if (response.code === 0) {
						t.url = e.url;
						t.submit()
					} else {
						// t.submit()
						// return
						t.url = ''
						t.$refs.upload.clear()
						t.$t.message.toast(response.msg)
					}
				}).catch(err => {
					t.$t.message.closeLoading()
					console.error(err)
				})
			},
			submit() {
				let t = this;
				t.$t.message.loading('正在签到')
				this.$request({
					url: this.$api.sign.add,
					method: 'POST',
					data: {
						mfid: t.mfid,
						lat: t.lat,
						lng: t.lng,
						province: t.province,
						city: t.city,
						county: t.county,
						street: t.street,
						address: t.address,
						url: t.url,
					}
				}).then(response => {
					t.$t.message.closeLoading()
					if (response.code === 0) {
						uni.showModal({
							title: '提示',
							content: response.msg,
							showCancel: false,
							success() {
								let url = `/pages/index`
								uni.redirectTo({
									url: url
								});
							}
						})

					}
				}).catch(err => {
					console.error(err)
					t.$t.message.toast(err)
				})
			},
			breakcheck() {
				uni.redirectTo({
					url: this.return_url,
				});
			},
			uperror(e) {
				// const logger = wx.getLogManager({
				// 	level: 1
				// })
				// logger.log(e, 'log', 100, [1, 2, 3])
				let t = this;
				let errstr = '上传失败，请重试'
				if (e) {
					errstr = JSON.stringify(e)
				}
				uni.showModal({
					title: '上传失败',
					content: errstr,
					success: function(res) {
						t.$refs.upload.clear()
					}
				});

				// 测试阶段 失败也跳转
				// let t = this;
				// uni.redirectTo({
				// 	url: t.return_url,
				// });
			},
			getLocation() {
				let t = this;
				//  #ifdef MP-WEIXIN
				wx.getLocation({
					type: 'gcj02',
					isHighAccuracy: true,
					success(res) {
						t.lat = res.latitude
						t.lng = res.longitude
						t.toaddress(res.latitude, res.longitude)
					},
					fail(err) {
						if (err.errMsg == 'getLocation:fail auth deny') {
							uni.showModal({
								title: '提示',
								content: '当前需要您的位置信息,去开启',
								success: function(res) {
									if (res.confirm) {
										uni.openSetting({
											success(res) {}
										});
									} else if (res.cancel) {
										t.goBack()
									}
								}
							});
						}
					}
				})
				// #endif
			},

			toaddress(latitude, longitude) {
				let t = this;
				qqmapsdk.reverseGeocoder({
					location: `${latitude},${longitude}`,
					success: function(response) {
						if (response) {
							let result = response.result
							let address_component = result && result.address_component
							t.province = address_component && address_component.province || ''
							t.city = address_component && address_component.city || ''
							t.county = address_component && address_component.district || ''
							t.street = result && result.address_reference && result.address_reference.town &&
								result.address_reference.town.title || ''
							t.address = result && result.formatted_addresses && result.formatted_addresses
								.standard_address || result.address || ''
							t.isaddress = true;
						}
					},
					fail: function(error) {
						console.error(error);
						uni.showModal({
							title: '提示',
							content: `获取位置失败，请联系管理员,${error.message}`,
							showCancel: false,
							success() {
								// t.goBack()
							}
						})
					},

				})
			},

			goBack() {
				// 通过判断当前页面的页面栈信息，是否有上一页进行返回，如果没有则跳转到首页
				const pages = getCurrentPages()
				if (pages && pages.length > 0) {
					const firstPage = pages[0]
					if (pages.length == 1 && (!firstPage.route || firstPage.route != 'pages/index')) {
						uni.reLaunch({
							url: '/pages/index'
						})
					} else {
						uni.navigateBack({
							delta: 1
						})
					}
				} else {
					uni.reLaunch({
						url: '/pages/index'
					})
				}
			},

		}
	}
</script>

<style lang="scss" scoped>
	.sign {
		width: 100%;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.btns {
		min-height: 400rpx;
	}

	.userinfo {
		display: flex;
		width: 100%;
		justify-content: flex-start;
		padding: 20rpx;
		border-radius: 15rpx;
		margin-bottom: 20rpx;
		margin-top: 30rpx;
	}

	.logo-image {
		width: 100rpx;
		height: 100rpx;
		border-radius: 15rpx;
		margin-right: 20rpx;
	}

	.signbg {
		width: 100%;
		padding-top: 140rpx;
		display: flex;
		align-items: center;
		flex-direction: column;
		height: 70vh;
		border-radius: 15rpx;
	}

	.desc {
		font-size: 28rpx;
	}

	.signbtn2 {
		width: 220rpx;
		height: 220rpx;
		background: $uni-text-color-grey;
		;
		color: #fff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		text-align: center;
		margin-bottom: 30rpx;
		margin-top: 100rpx;
	}

	.signbtn {
		width: 220rpx;
		height: 220rpx;
		background: #2074d4;
		color: #fff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		text-align: center;
		margin-bottom: 30rpx;
		margin-top: 100rpx;

		.text {
			padding-bottom: 10rpx;
			font-weight: bold;
		}

		.time {
			font-size: 26rpx;
		}
	}

	.address {
		color: $uni-text-color-grey;
		font-size: 26rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}




	/* 底部安全边距 start*/
	.tn-tabbar-height {
		min-height: 120rpx;
		height: calc(140rpx + env(safe-area-inset-bottom) / 2);
		height: calc(140rpx + constant(safe-area-inset-bottom));
	}
</style>